<?php

namespace app\admin\server;

class BaseServer
{

    //发送get请求
    public static function httpCurlGetRequest($url, $timeout = 5)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, (int)$timeout);
        $data = curl_exec($curl);
        if(curl_errno($curl)) {
            return 'ERROR' . curl_error($curl);
        }
        curl_close($curl);
        return json_decode($data, true);
    }

    //发送post请求
    public static function httpCurlPostRequest($url, $post_data)
    {
        //初始化
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        if(curl_errno($curl)) {
            return 'Errno' . curl_errno($curl);
        }
        curl_close($curl);
        //显示获得的数据
        return json_decode($result, true);
    }

    /**
     * @param $data
     * @return void
     */
    public static function parseXml($data)
    {
        if(empty($data)) return $data;

    }

    /**
     * xml 转 array
     * @param $xml
     * @return array|mixed
     */
    public static function xmlToArray($xml)
    {
        $reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/";
        if(preg_match_all($reg, $xml, $matches)) {
            $count = count($matches[0]);
            $arr = array();
            for($i = 0; $i < $count; $i++) {
                $key = $matches[1][$i];
                $val = self::xmlToArray($matches[2][$i]);  // 递归
                if(array_key_exists($key, $arr)) {
                    if(is_array($arr[$key])) {
                        if(!array_key_exists(0, $arr[$key])) {
                            $arr[$key] = array($arr[$key]);
                        }
                    } else {
                        $arr[$key] = array($arr[$key]);
                    }
                    $arr[$key][] = $val;
                } else {
                    $arr[$key] = $val;
                }
            }
            return $arr;
        } else {
            return $xml;
        }
    }

    /**
     * xml 转 array
     * @param $xml
     * @return array|mixed
     */
    public static function xmlToArray2($xml)
    {
        $arr = self::xmlToArray($xml);
        $key = array_keys($arr);
        return $arr[$key[0]];
    }

}